package com.custom.base.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import com.google.android.material.appbar.AppBarLayout
import com.custom.base.R
import com.custom.base.manager.SDFragmentManager
import com.sunday.eventbus.SDBaseEvent
import com.sunday.eventbus.SDEventManager
import com.sunday.eventbus.SDEventObserver

/**
 * 作者：
 * 时间：2020/12/8
 * 描述：
 **/
abstract class BaseFragment : BaseActivityFragment(), SDEventObserver {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val arguments = arguments
        arguments?.apply { initParms(arguments) }
        mActivity = activity!!
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mContextView = bindView() ?: inflater.inflate(bindLayout(), container, false)
        mContextView = getContentView(mContextView)
        SDEventManager.unregister(this)
        SDEventManager.register(this)
        return mContextView
    }

    private fun getContentView(mContextView: View): View {
        val baseView = layoutInflater.inflate(R.layout.act_base, null)
        baseView.findViewById<LinearLayout>(R.id.actBaseContent).addView(mContextView)
        return baseView
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initTitle(setTitleVisibility())
        initView(mContextView)
    }

    /**
     * 初始化title
     */
    private fun initTitle(titleVisibility: Boolean) {
        if (titleVisibility) {
            getTitleTextView(mContextView.findViewById(R.id.actBaseTitleView))
            getToolbarView(mContextView.findViewById(R.id.actBaseToolbar))
            getAppBarLayoutView(mContextView.findViewById(R.id.ActBaseAppBarLayout))
        } else mContextView.findViewById<AppBarLayout>(R.id.ActBaseAppBarLayout).visibility =
            View.GONE
    }

    /**
     * 获取FragmentManager
     *
     * @return
     */
    fun getSDFragmentManager(): SDFragmentManager {
        if (mFManager == null) {
            mFManager = SDFragmentManager(childFragmentManager)
        }
        return mFManager as SDFragmentManager
    }

    override fun onEvent(event: SDBaseEvent) {}

    override fun onEventMainThread(event: SDBaseEvent) {}

    override fun onEventBackgroundThread(event: SDBaseEvent) {}

    override fun onEventAsync(event: SDBaseEvent) {}

    override fun onDestroy() {
        super.onDestroy()
        SDEventManager.unregister(this)
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onPause() {
        super.onPause()
    }
}
